import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Response } from 'express';
import { formatError } from './index';

// 捕获所有异常
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    console.error('==== 全局异常捕获 ====', exception);
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    // 是否是第三方的status
    const isThird = exception?.requestOptions?.baseUrl.includes('gateio.ws') ? true : false;
    const status: any = isThird ? exception?.code : exception?.getStatus ? exception?.getStatus() : 500;
    const myMsg =
      exception instanceof HttpException
        ? // message有字符串和数组(validator)两种格式，此处将数组取第一个数据
          Array.isArray(exception?.getResponse()['message'])
          ? exception?.getResponse()['message'][0]
          : exception?.getResponse()['message']
        : 'Internal server error';
    // 格式化错误返回
    const errorResponse = formatError({ msg: isThird ? `${exception?.body?.label}：${exception?.body?.message}` : myMsg });
    // 将validator的错误400转化为业务错误
    const _status = status === 400 ? 200 : status;
    response.status(_status).json(errorResponse);
  }
}
